package main

import (
	"gobindc_test/server/model"
	utils2 "gobindc_test/server/utils"
	"log"
	"net"
	"os"
	"strconv"
)

func main() {
	confFilePath := "./conf/settings_conf.ini"
	if len(os.Args) > 1 {
		confFilePath = os.Args[1]
	}
	dataConfig := utils2.GetConfig(confFilePath)
	socket, err := net.Listen(dataConfig.ServerDeal, dataConfig.ServerIP+":"+strconv.Itoa(dataConfig.ServerPort))
	if err != nil {
		log.Fatalln(err.Error())
	}
	defer func(socket net.Listener) {
		err := socket.Close()
		if err != nil {
			log.Fatalln(err.Error())
		}
	}(socket)
	if dataConfig.DataSeat == "ram" {
		sqList := model.SqList{
			DataList: make([]*model.MyData, dataConfig.DataLength),
			Length:   0,
		}
		for {
			conn, err := socket.Accept()
			if err != nil {
				log.Fatalln(err.Error())
			}
			go utils2.HandleConnInRam(conn, &sqList, *dataConfig)
		}
	} else if dataConfig.DataSeat == "disk" {
		sqList := model.SqListDisk{
			DataFilePath: dataConfig.DataDiskFile,
			Lines:        utils2.GetFileLine(dataConfig.DataDiskFile),
			Length:       dataConfig.DataLength,
		}
		for {
			conn, err := socket.Accept()
			if err != nil {
				log.Fatalln(err.Error())
			}
			go utils2.HandleConnInDisk(conn, &sqList, *dataConfig)
		}
	}
	/*	hash := sha256.New()
		hash.Write([]byte("123456"))
		sum := hash.Sum(nil)
		password := hex.EncodeToString(sum)
		request := model.SocketDataRequest{
			Password: password,
			Cmd:      "get",
			Data:     "test",
		}
		marshal, _ := json.Marshal(request)
		fmt.Println(string(marshal))
		request.Cmd = "set"
		bytes, _ := json.Marshal(request)
		fmt.Println(string(bytes))*/
}
